package cn.yunyichina.provider.register.service.impl;

import cn.yunyichina.provider.framework.dubbo.service.OrderService;
import cn.yunyichina.provider.framework.dubbo.service.RegisterService;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.order.OrderRegSchedulerVo;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * Created by Administrator on 2017/5/22.
 */
@Service
public class RegSchedulerServiceImpl {

    @Autowired
    private StopRegServiceImpl stopRegService;

    @Autowired
    private RegRecordServiceImpl regRecordService;

    private static int UNLOCK_MAX_COUNT = 10;//解锁的重试最大次数

    /** 挂号定时器任务执行（解锁，停诊）
     * yyt.register.reg.scheduler.do
     * @param data
     * @param sessionId
     * @return
     * @throws Exception
     */
    public Response doRegScheduler(String data, String sessionId) throws Exception {
        Response response = new Response();
        /**轮询停诊失败订单*/
        OrderRegSchedulerVo query = new OrderRegSchedulerVo();
        query.setOrderStatus(OrderExtVo.ORDER_STATUS_CHANGE);
        query.setStopStatus((short) 2);
        List<OrderRegSchedulerVo> list = OrderService.getOrderClient().findOrderRegScheduler(query);
        if(!CollectionUtils.isEmpty(list)){
            for(OrderRegSchedulerVo vo:list){
                stopRegService.dealStopSchedulerVo(vo);
            }
        }
        /**轮询停诊失败订单结束*/

        /**轮询解锁失败订单*/
        query = new OrderRegSchedulerVo();
        query.setOrderStatus(OrderExtVo.ORDER_STATUS_CANCEL);
        query.setUnlockResult((short) 2);
        list = OrderService.getOrderClient().findOrderRegScheduler(query);
        if(!CollectionUtils.isEmpty(list)){
            for(OrderRegSchedulerVo schedulerVo:list){
                if(schedulerVo.getUnlockCount() != null && schedulerVo.getUnlockCount() >= UNLOCK_MAX_COUNT){
                    continue;
                }
                String unlockData = "{\"order_no\":\"" + schedulerVo.getOrderNo() + "\"}";
                Response unlocdResp = regRecordService.unlockRegRecord(unlockData,sessionId);
                if ("0".equals(unlocdResp.getResultCode())) {
                    schedulerVo.setUnlockResult((short) 1);
                } else {
                    schedulerVo.setUnlockResult((short) 2);
                }
                schedulerVo.setUnlockResult((short) (schedulerVo.getUnlockCount() + 1));
                OrderService.getOrderClient().updateOrderRegScheduler(schedulerVo);
            }
        }
        /**轮询解锁失败订单结束*/

        response.setResultCodeAndMessage("0","成功");
        return response;
    }
}
